<template>
  <div class="admin-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="searchParams.username" placeholder="请输入用户名" clearable @keyup.enter.native="searchByUsername">
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-input v-model="searchParams.email" placeholder="请输入邮箱" clearable @keyup.enter.native="searchByEmail">
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="searchByUsername">搜索用户名</el-button>
          <el-button type="primary" @click="searchByEmail">搜索邮箱</el-button>
          <el-button type="success" @click="showAddDialog">新增</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 信息展示区 -->
    <div class="table-container">
      <el-table :data="tableData" style="width: 100%" border v-if="tableData.length > 0">
        <el-table-column prop="username" label="用户名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
		<el-table-column prop="role" label="角色">
		</el-table-column>
        <el-table-column prop="create_time" label="创建时间">
          <template slot-scope="scope">
            {{ formatDate(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="update_time" label="更新时间">
          <template slot-scope="scope">
            {{ formatDate(scope.row.update_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-else class="no-data">
        <p>没有找到匹配的数据</p>
      </div>
    </div>
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="currentPage" :page-size.sync="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="allData.length">
      </el-pagination>
    </div>
    <!-- 编辑对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="30%" v-if="currentRow"
      @close="currentRow = null">
      <el-form :model="currentRow" :rules="editRules" ref="editForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="currentRow.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentRow.email"></el-input>
        </el-form-item>
		<el-form-item label="角色" prop="role">
			<el-select v-model="currentRow.role" placeholder="请选择角色">
				<el-option label="管理员" value="管理员"></el-option>
				<el-option label="超级管理员" value="超级管理员"></el-option>
			</el-select>
		</el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate">更新</el-button>
      </span>
    </el-dialog>
    <!-- 新增对话框 -->
    <el-dialog title="新增用户" :visible.sync="addDialogVisible" width="30%">
      <el-form :model="addUser" :rules="addRules" ref="addForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUser.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUser.email"></el-input>
        </el-form-item>
		<el-form-item label="验证码" prop="code">
		  <el-input v-model="addUser.code"></el-input>
		  <el-button type="primary" @click="sendVerificationCode" class="code1">获取验证码</el-button>
		</el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addUser.password"></el-input>
        </el-form-item>
        <el-form-item label="确定密码" prop="confirmPassword">
          <el-input type="password" v-model="addUser.confirmPassword"></el-input>
        </el-form-item>
		<el-form-item label="用户角色" prop="role">
			<el-select v-model="addUser.role" placeholder="请选择用户角色">
				<el-option label="管理员" value="管理员"></el-option>
				<el-option label="超级管理员" value="超级管理员"></el-option>
			</el-select>
		</el-form-item>
<!-- 		<el-form-item label="用户角色" prop="role">
		  <el-input type="role" v-model="addUser.role"></el-input>
		</el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import {
  Input,
  Row,
  Col,
  Button,
  Table,
  TableColumn,
  Dialog,
  Form,
  FormItem,
  Pagination,
  Message
} from 'element-ui';

export default {
  name: 'UserTable',
  components: {
    'el-input': Input,
    'el-row': Row,
    'el-col': Col,
    'el-button': Button,
    'el-table': Table,
    'el-table-column': TableColumn,
    'el-dialog': Dialog,
    'el-form': Form,
    'el-form-item': FormItem,
    'el-pagination': Pagination
  },
  data() {
	   const validateRole = (rule, value, callback) => {
	        if (value === '') {
	          callback(new Error('请输入用户角色'));
	        } else if (value !== '超级管理员' && value !== '管理员') {
	          callback(new Error('角色只能是“超级管理员”或“管理员”'));
	        } else {
	          callback(); // 验证通过
	        }
	      };
    return {
      allData: [], // 存储所有数据
      tableData: [], // 存储当前页的数据
      searchParams: {
        username: '',
        email: ''
      },
      editDialogVisible: false,
      currentRow: {
        username: '',
        email: '',
		role:'',
        id: null
      },
      addDialogVisible: false,
      addUser: {
        username: '',
        email: '',
        password: '',
        confirmPassword: '',
        code: ''
      },
      editRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 15, message: '用户名长度为3-15个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur,change' }
        ],
        role: [
           { required: true, message: '请输入用户角色', trigger: 'blur' },
                   { validator: validateRole, trigger: 'blur' }
        ]
      },
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 15, message: '用户名长度为3-15个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur,change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur' }
        ],
		role: [
           { required: true, message: '请输入用户角色', trigger: 'blur' },
                   { validator: validateRole, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.addUser.password) {
                callback(new Error('两次密码输入不一致'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      currentPage: 1,
      pageSize: 10,
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      const token = localStorage.getItem('Authorization');
      if (!token) {
        this.$message.error('未授权访问');
        return;
      }
      const headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': token
      };
      axios.get('http://localhost:8887/admin/adminfindAll', { headers })
        .then(response => {
          if (response.data.code === 200) {
            this.allData = response.data.data.map(item => ({
              username: item.username,
              email: item.email,
			  role:item.role,
              create_time: item.create_time,
              update_time: item.update_time,
              id: item.id
            }));
            this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
          } else {
            this.$message.error('获取数据失败: ' + response.data.message);
          }
        })
        .catch(error => {
          console.error('请求失败:', error);
          this.$message.error('请求失败，请检查网络或联系管理员');
        });
    },
	formatDate(value) {
	    const date = new Date(value);
	    return new Intl.DateTimeFormat('zh-CN', {
	      year: 'numeric',
	      month: '2-digit',
	      day: '2-digit',
	      hour: '2-digit',
	      minute: '2-digit',
	      second: '2-digit',
	      hour12: false
	    }).format(date);
	  },
    searchByUsername() {
      const token = localStorage.getItem('Authorization');
      const headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': token,
		  };
		  axios.get('http://localhost:8887/admin/selectusername', {
		    headers,
		    params: {
		      username: this.searchParams.username
		    }
		  })
		  .then(response => {
		    if (response.data.code === 200 && response.data.data.length > 0) {
		      this.allData = response.data.data;
		      this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
		      this.currentPage = 1; // 重置当前页为 1
		    } else {
		      this.$message.error(response.data.message || '未找到匹配的用户');
		      this.tableData = []; // 清空表格数据
		    }
		  })
		  .catch(error => {
		    console.error('请求失败:', error);
		    this.$message.error('请求失败，请检查网络或联系管理员');
		  });
		},
		searchByEmail() {
		  const token = localStorage.getItem('Authorization');
		  const headers = {
		    'Content-Type': 'application/x-www-form-urlencoded',
		    'Authorization': token
		  };
		  axios.get('http://localhost:8887/admin/selectemail', {
		    headers,
		    params: {
		      email: this.searchParams.email
		    }
		  })
		  .then(response => {
		    if (response.data.code === 200 && response.data.data.length > 0) {
		      this.allData = response.data.data;
		      this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
		      this.currentPage = 1; // 重置当前页为 1
		    } else {
		      this.$message.error(response.data.message || '未找到匹配的用户');
		      this.tableData = []; // 清空表格数据
		    }
		  })
		  .catch(error => {
		    console.error('请求失败:', error);
		    this.$message.error('请求失败，请检查网络或联系管理员');
		  });
		},
		handleEdit(row) {
		  if (row) {
		    this.currentRow = { ...row };
		    this.editDialogVisible = true;
		  } else {
		    console.error('Error: Row data is null');
		  }
		},
		handleUpdate() {
		  this.$refs.editForm.validate((valid) => {
		    if (valid) {
		      const token = localStorage.getItem('Authorization');
		      const headers = {
		        'Content-Type': 'application/json',
		        'Authorization': token
		      };
		      axios.post('http://localhost:8887/admin/updateAdminById', this.currentRow, { headers })
		        .then(response => {
		          if (response.data.code === 200) {
		            this.$message.success('更新成功');
		            this.editDialogVisible = false;
		            this.fetchData();
		          } else {
		            this.$message.error('更新失败: ' + response.data.message);
		          }
		        })
		        .catch(error => {
		          console.error('请求失败:', error);
		          this.$message.error('请求失败，请检查网络或联系管理员');
		        });
		    } else {
		      this.$message.error('表单验证失败');
		    }
		  });
		},
		handleDelete(id) {
		  this.$confirm('确认删除这条记录吗?', '提示', {
		    type: 'warning'
		  }).then(() => {
		    const token = localStorage.getItem('Authorization');
		    const headers = {
		      'Content-Type': 'application/x-www-form-urlencoded',
		      'Authorization': token
		    };
		    axios.post('http://localhost:8887/admin/deleteAdminById?id=' + id, null, { headers })
		      .then(response => {
		        if (response.data.code === 200) {
		          this.$message.success('删除成功');
		          this.fetchData(); // 重新加载数据
		        } else {
		          this.$message.error('删除失败: ' + response.data.message);
		        }
		      })
		      .catch(error => {
		        console.error('请求失败:', error);
		        this.$message.error('请求失败，请检查网络或联系管理员');
		      });
		  }).catch(() => {
		    this.$message.info('已取消删除');
		  });
		},
		showAddDialog() {
		  this.addDialogVisible = true;
		  this.addUser = {
		    username: '',
		    email: '',
		    password: '',
		    confirmPassword: '',
		    code: '',
			role:''
		  };
		},
		sendVerificationCode() {
		  const url = 'http://localhost:8887/admin/sendCode';
		  axios.get(url, {
		    params: {
		      email: this.addUser.email
		    }
		  })
		  .then(response => {
		    if (response.data.code === 200) {
		      this.$message.success('验证码发送成功，请查收邮件');
		    } else {
		      this.$message.error('验证码发送失败: ' + response.data.message);
		    }
		  })
		  .catch(error => {
		    console.error('请求失败:', error);
		    this.$message.error('请求失败，请检查网络或联系管理员');
		  });
		},
		handleAdd() {
		  this.$refs.addForm.validate((valid) => {
		    if (valid) {
		      const token = localStorage.getItem('Authorization');
		      const headers = {
		        'Content-Type': 'application/json',
		        'Authorization': token
		      };
		      axios.post('http://localhost:8887/admin/register', this.addUser, { headers })
		        .then(response => {
		          if (response.data.code === 200) {
		            this.$message.success('新增用户成功');
		            this.addDialogVisible = false;
		            this.fetchData();
		          } else {
		            this.$message.error('新增用户失败: ' + response.data.message);
		          }
		        })
		        .catch(error => {
		          console.error('请求失败:', error);
		          this.$message.error('请求失败，请检查网络或联系管理员');
		        });
		    } else {
		      this.$message.error('表单验证失败');
		    }
		  });
		},
		handleSizeChange(newSize) {
		  this.pageSize = newSize;
		  this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
		},
		handleCurrentChange(newPage) {
		  this.currentPage = newPage;
		  this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
		},
		},
		};
		</script>
		<style scoped>
		.admin-container {
		  padding: 20px;
		  max-width: 100%; /* 确保容器的宽度不超过视口宽度 */
		  overflow-x: auto; /* 如果需要，启用水平滚动 */
		}
		
		.search-bar {
		  margin-bottom: 20px;
		}
		
		.search-bar .el-row {
		  display: flex;
		  justify-content: space-between; /* 为新增按钮留出空间 */
		}
		
		.search-bar .el-button {
		  margin-left: 10px; /* 为按钮之间添加一些间距 */
		}
		
		.table-container {
		  margin-top: 20px;
		  overflow-x: auto; /* 如果需要，为表格启用水平滚动 */
		}
		
		.no-data {
		  text-align: center;
		  padding: 20px;
		}
		
		.pagination-container {
		  margin-top: 20px;
		  text-align: left; /* 将分页组件移到左侧 */
		}
		
		.dialog-footer {
		  text-align: right; /* 对话框底部按钮右对齐 */
		}
		
		.el-dialog__body {
		  padding: 20px; /* 对话框内容区域的内边距 */
		}
		
		.el-form-item {
		  margin-bottom: 20px; /* 表单项之间的间距 */
		}
		.code1{
			margin-top: 10px;
		}
		.el-form-item__label {
		  font-weight: bold; /* 标签字体加粗 */
		}
		
		.el-button--primary {
		  background-color: #13ce66;
		  border-color: #13ce66;
		}
		
		.el-button--primary:hover {
		  background-color: #11b55e;
		  border-color: #11b55e;
		}
		</style>